package hu.ibm.web;

import hu.ibm.model.Address;
import hu.ibm.model.Role;
import hu.ibm.model.User;
import hu.ibm.service.UserService;
import hu.ibm.web.user.Gender;
import hu.ibm.web.user.MaritalStatus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@ManagedBean(name = "userBean")
@RequestScoped
public class UserBean {
	@ManagedProperty(value = "#{userService}")
	private UserService userService;

	private User user = new User();
	private String passwordConfirm;
	private String emailConfirm;

	private static Logger logger = Logger.getLogger(UserBean.class);

	public UserBean() {
		super();

		logger.debug("UserBean create usersercice" + userService);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

	public List<User> getAllUser() {
		return getUserService().getUsers();
	}

	public String addUser() throws ValidatorException {
		try {
			
			if (getUserService() != null) {
				getUserService().createNewUser(user);
			}
		} catch (Exception e) {
			e.printStackTrace();

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					e.getMessage(), null);
			throw new ValidatorException(msg);
		}
		return "";
	}

	public String modUser() throws ValidatorException {
		try {

			getUserService().merge(user);

		} catch (Exception e) {
			// TODO: handle exception

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					e.getMessage(), null);
			throw new ValidatorException(msg);
		}
		return "";
	}

	public String delUser() throws ValidatorException {
		try {

			getUserService().remove(user);

		} catch (Exception e) {
			// TODO: handle exception

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					e.getMessage(), null);
			throw new ValidatorException(msg);
		}
		return "";
	}

	public User getUser() {
		if(user==null){
			user= new User();
			
		}
		if(user.getAddress()==null){
			user.setAddress(new Address());
		}
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List getGenders() {
		ArrayList genders = new ArrayList();
		MessageFactory msg = new MessageFactory();

		SelectItem item = new SelectItem();
		item.setLabel(msg.getMessage("male"));
		item.setValue(Gender.Male.toString());
		genders.add(item);
		item = new SelectItem();
		item.setLabel(msg.getMessage("female"));
		item.setValue(Gender.Female.toString());
		genders.add(item);
		item = new SelectItem();
		item.setLabel(msg.getMessage("undisclosed"));
		item.setValue(Gender.Undisclosed.toString());
		genders.add(item);
		return genders;
	}

	public List getMaritalStati() {
		ArrayList maritalStati = new ArrayList();
		MessageFactory msg = new MessageFactory();

		SelectItem item = new SelectItem();
		item.setLabel(msg.getMessage("married"));
		item.setValue(MaritalStatus.Married.toString());
		maritalStati.add(item);
		item = new SelectItem();
		item.setLabel(msg.getMessage("single"));
		item.setValue(MaritalStatus.Single.toString());
		maritalStati.add(item);
		item = new SelectItem();
		item.setLabel(msg.getMessage("undisclosed"));
		item.setValue(MaritalStatus.Undisclosed.toString());
		maritalStati.add(item);
		return maritalStati;
	}

	public String register() throws Exception {
		String toReturn = "failure";

		if (validateData()) {
			try {
				// save locale information, in case the user chose a language on
				// the welcome page
				Locale locale = FacesContext.getCurrentInstance().getViewRoot()
						.getLocale();
				user.setLocaleCountry(locale.getCountry());
				user.setLocaleLanguage(locale.getLanguage());
				user.setRoles(Role.ROLE_REGISTERED.name());
				user.setActive(true);
				addUser();
				toReturn = "success";

			} catch (Exception exist) {
				exist.printStackTrace();
				MessageFactory msg = new MessageFactory();
				FacesContext ctx = FacesContext.getCurrentInstance();

				ctx.addMessage(
						"registerForm:email",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, msg
								.getMessage("errorEmailExists"), null));
			}
		}
		return toReturn;
	}

	private boolean validateData() {
		boolean toReturn = true;
		MessageFactory msg = new MessageFactory();
		FacesContext ctx = FacesContext.getCurrentInstance();

		// check emailConfirm is same as email
		if (!emailConfirm.equals(user.getEmail())) {
			ctx.addMessage(
					"registerForm:emailConfirm",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, msg
							.getMessage("errorEmailConfirm"), null));
			toReturn = false;
		}
		// check passwordConfirm is same as password
		if (!passwordConfirm.equals(user.getPassword())) {
			ctx.addMessage(
					"registerForm:passwordConfirm",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, msg
							.getMessage("errorPasswordConfirm"), null));
			toReturn = false;
		}
		return toReturn;
	}

	public String getEmailConfirm() {
		return emailConfirm;
	}

	public void setEmailConfirm(String emailConfirm) {
		this.emailConfirm = emailConfirm;
	}

	public String getPasswordConfirm() {
		return passwordConfirm;
	}

	public void setPasswordConfirm(String passwordConfirm) {
		this.passwordConfirm = passwordConfirm;
	}

}